package com.fzq.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Excel 导出工具类（基于 Apache POI）
 */
public class CommonExportExcel {

    /**
     * 导出 Excel 文件到字节数组输出流
     *
     * @param title       Excel 文件标题集合，每个 Map 包含 mapping_name 和 column_name
     * @param listContent Excel 文件正文数据集合
     * @param os          字节数组输出流
     * @return 操作结果信息
     */
    public static String exportExcel(List<Map<String, Object>> title, List<? extends Map<String, Object>> listContent, ByteArrayOutputStream os) {
        String result = "系统提示：Excel文件导出成功！";

        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet("Sheet1");

            // 创建样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle contentStyle = createContentStyle(workbook);

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < title.size(); i++) {
                Cell cell = headerRow.createCell(i);
                String titleVal = String.valueOf(title.get(i).get("mapping_name"));
                if ("null".equals(titleVal)) {
                    titleVal = "";
                }
                cell.setCellValue(titleVal);
                cell.setCellStyle(headerStyle);

                // 设置列宽自适应
                sheet.autoSizeColumn(i);
            }

            // 填充数据行
            for (int i = 0; i < listContent.size(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                Map<String, Object> data = listContent.get(i);

                for (int j = 0; j < title.size(); j++) {
                    Cell cell = dataRow.createCell(j);
                    String colName = String.valueOf(title.get(j).get("column_name"));
                    Object value = data.get(colName);

                    if (value != null) {
                        setCellValue(cell, value);
                    } else {
                        cell.setCellValue("");
                    }
                    cell.setCellStyle(contentStyle);
                }
            }

            // 写入输出流
            workbook.write(os);

        } catch (Exception e) {
            result = "系统提示：Excel文件导出失败，原因：" + e.getMessage();
            System.out.println(result);
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 创建标题行样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();

        // 设置字体
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 10);
        font.setBold(true);

        // 设置样式
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);

        return style;
    }

    /**
     * 创建内容行样式
     */
    private static CellStyle createContentStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();

        // 设置字体
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 10);

        // 设置样式
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;
    }

    /**
     * 根据值的类型设置单元格内容
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof java.util.Date) {
            cell.setCellValue((java.util.Date) value);
        } else if (value instanceof java.time.LocalDate) {
            cell.setCellValue(java.sql.Date.valueOf((java.time.LocalDate) value));
        } else if (value instanceof java.time.LocalDateTime) {
            cell.setCellValue(java.sql.Timestamp.valueOf((java.time.LocalDateTime) value));
        } else {
            cell.setCellValue(value.toString());
        }
    }

    /**
     * 导出 Excel 文件并返回字节数组
     *
     * @param title       Excel 文件标题集合
     * @param listContent Excel 文件正文数据集合
     * @return 包含 Excel 文件的字节数组
     */
    public static byte[] exportExcelToBytes(List<Map<String, Object>> title, List<? extends Map<String, Object>> listContent) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            exportExcel(title, listContent, os);
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }
}